<template>
  <a-modal :visible="visible" title="上传补充资料" @ok="handleOk" @cancel="() => { $emit('cancel') }">
    <div style="min-height: 120px;">
      <a-spin :spinning="loading">
        <a-form v-if="showForm" :form="form" >
          <a-form-item>
            <a-upload
              name="file"
              action="/grade-evaluation-api/minio/uploadFile"
              :headers="headers"
              :before-upload="beforeAssessmentUpload"
              v-decorator="[
                'fileList',
                {
                  rules: [{required: false}],
                  valuePropName: 'fileList',
                  initialValue: initialValue,
                  getValueFromEvent: normFile,
                },
              ]"
            >
              <a-button icon="upload">点击上传</a-button>
              <span style="margin-left: 15px;">只能上传zip压缩包</span>
            </a-upload>
          </a-form-item>
        </a-form>
      </a-spin>
    </div>
  </a-modal>
</template>

<script>
import { ACCESS_TOKEN } from '@/store/mutation-types'
import pick from 'lodash.pick'
import storage from 'store'
import { getFileList, batchSaveDataFile } from '@/api/system'
// 表单字段
const fields = ['id', 'parentId', 'target', 'sort', 'serialNumber', 'totalPoint', 'mustFlag', 'comment', 'backUpData', 'fileList']
export default {
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      form: this.$form.createForm(this),
      loading: false,
      showForm: true,
      initialValue: [],
      headers: {
        authorization: storage.get(ACCESS_TOKEN)
      }
    }
  },
  watch: {
    visible (val) {
      this.initialValue = []
      if (val) {
        this.getList()
      }
    }
  },
  created () {
     // 防止表单未注册
     fields.forEach(v => this.form.getFieldDecorator(v))

    // 当 model 发生改变时，为表单设置值
    this.$watch('visible', () => {
      this.visible && this.form.setFieldsValue(pick(this.visible, fields))
    })
  },
  methods: {
    handleOk () {
      this.form.validateFields((errors, values) => {
        if (!errors) {
          const params = []
          values.fileList.map(item => {
            params.push({
              declarationInfoId: this.$route.query.declarationInfoId,
              fileId: item.uid
            })
          })
          this.loading = true
          batchSaveDataFile(params).then(() => {
            this.$message.success('操作成功')
            this.$emit('ok')
          }).finally(() => {
            this.loading = false
          })
        }
      })
    },
    getList () {
      this.loading = true
      getFileList(this.$route.query.declarationInfoId).then(res => {
        this.showForm = false
        res.map(item => {
          if (item.file) {
            // 兼容旧文件
            let fileData = item.file
            let docUrl = process.env.VUE_APP_OSS_API + fileData.url
            if (!fileData.bucketName) {
              docUrl = fileData.url.indexOf('pinggu.mkcom.cn') > -1 ? fileData.url : process.env.VUE_APP_FILE_API + fileData.url
            }
            this.initialValue.push({
              uid: item.file.id,
              name: item.file.original,
              status: 'done',
              url: docUrl
            })
          }
        })
        setTimeout(() => {
          this.showForm = true
        })
      }).finally(() => {
        this.loading = false
      })
    },
    beforeAssessmentUpload (file) {
      console.log(file)
      const fileType = file.name.split('.')
      const fileFormat = fileType.slice(-1)
      const isPdfOrWord = ['zip'].indexOf(fileFormat[0]) > -1
      const is200M = file.size / 1024 / 1024 < 200
      if (!isPdfOrWord) {
        this.$message.error('只能上传zip格式!')
      }
      if (!is200M) {
        this.$message.error('只能上传200M以内的文件!')
      }
      return isPdfOrWord && is200M
    },
    normFile (e) {
      console.log('Upload img event:', e)
      // if (e.fileList.length > 1) {
      //     // 限制只上传一个文件，再次上传时则替换(覆盖)以前的文件
      //     // splic(0,1)是把第一个删除
      //     e.fileList.splice(0, 1)
      // }
      if (e.file.status === 'uploading' || e.file.status === 'removed') {
        return e && e.fileList
      }
      if (e.file.status === 'done') {
        const list = []
        e.fileList.forEach(item => {
          if (item.response) {
            const { id, original, url, fileSize } = item.response.data
            list.push({
              uid: id,
              name: original,
              status: 'done',
              url: process.env.VUE_APP_OSS_API + url,
              fileSize: fileSize
            })
          } else {
            list.push(item)
          }
        })
        return list
      }
    }
  }
}
</script>
<style></style>
